import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/login'
import Layout from '@/views/layout'
import Myorder from '@/views/myorder'
import Prodetail from '@/views/prodetail'
import Pay from '@/views/pay'
import Search from '@/views/search'
import SearchList from '@/views/search/list.vue'

import Home from '@/views/layout/home'
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import User from '@/views/layout/user'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [{
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [{
      path: '/home',
      component: Home
    },
    {
      path: '/cart',
      component: Cart
    },
    {
      path: '/category',
      component: Category
    },
    {
      path: '/user',
      component: User
    }
    ]
  },
  {
    path: '/myorder',
    component: Myorder
  },
  {
    path: '/pay',
    component: Pay
  },
  {
    path: '/prodetail/:id',
    component: Prodetail
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/SearchList',
    component: SearchList
  }
  ]
})

// 路由前置守卫
const authUrls = ['/Pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 在auth名单之外的直接放行
  if (!authUrls.includes(to.path)) {
    next()
  }
  // auath名单判断是否带token
  if (store.getters.token) {
    next()
  } else {
    next('/login')
  }
})

export default router
